package main

import (
	"context"
	"errors"
	"fmt"
	"github.com/mark3labs/mcp-go/mcp"
	"github.com/mark3labs/mcp-go/server"
	"os"
)

// https://mp.weixin.qq.com/s/35ougfW9Jf8S0lMmiwG9Rw
func main() {
	s := server.NewMCPServer("Server Demo", "1.0.0")

	// 添加工具
	calculatorTool := mcp.NewTool("calculate",
		mcp.WithDescription("执行基本的算术运算"),
		mcp.WithString("operation",
			mcp.Required(),
			mcp.Description("要执行的算术运算类型"),
			mcp.Enum("multiply", "divide"),
		),
		mcp.WithNumber("x",
			mcp.Required(),
			mcp.Description("第一个数字"),
		),
		mcp.WithNumber("y",
			mcp.Required(),
			mcp.Description("第二个数字"),
		),
	)

	s.AddTool(calculatorTool, func(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
		arguments, ok := request.Params.Arguments.(map[string]any)
		if !ok {
			return nil, errors.New("Arguments must be a map")
		}
		op := arguments["operation"].(string)
		x := arguments["x"].(float64)
		y := arguments["y"].(float64)

		var result float64
		switch op {
		case "multiply":
			result = x * y
		case "divide":
			if y == 0 {
				return nil, errors.New("不允许除以零")
			}
			result = x / y
		}

		return mcp.FormatNumberResult(result), nil
	})

	resource := mcp.NewResource(
		"docs://readme",
		"项目说明文档",
		mcp.WithResourceDescription("项目的 README 文件"),
		mcp.WithMIMEType("text/markdown"),
	)

	// 为资源添加处理函数
	handler := func(ctx context.Context, request mcp.ReadResourceRequest) ([]mcp.ResourceContents, error) {
		// 读取 README 文件内容
		content, err := os.ReadFile("README.md")
		if err != nil {
			return nil, err
		}

		return []mcp.ResourceContents{
			mcp.TextResourceContents{
				URI:      "docs://readme",
				MIMEType: "text/markdown",
				Text:     string(content),
			},
		}, nil
	}

	s.AddResource(resource, handler)

	// 启动基于 stdio 的服务器
	if err := server.ServeStdio(s); err != nil {
		fmt.Printf("Server error: %v\n", err)
	}
}
